var wineApp = wineApp || {};
wineApp.shopcar = (function() {
    var initPage = function() {
        initShopcarPage();
        initSpinbox();
        initEvent();
        //loadAddr();
    }
    var addrId = "";
    var wineId = "";
    var totalTotal = 0; //总金额
    var key = wineApp.CONFIG.STORAGE.PREFIX + '.' + 'userInfo.msg';
    var countPerSet = wineApp.CONFIG.countPerSet;
    var userInfo = wineApp.localStorage.get(key);
    var resourceURL = wineApp.tool.getResourceURL();
    var shopcarList = [];
    var initSpinbox = function() {
        $(document)
            .on('click', '.spin-minus', function() {
                var id = $(this).attr("id");
                id = id.replace("minus_", "");
                var val = parseInt($('#spin-value_' + id).val(), 10);
                if (val <= 1) {
                    val = 1;
                    $('#spin-value_' + id).val(val);
                } else {
                    val = val - 1;
                    $('#spin-value_' + id).val(val);
                }
                $('#check_' + id).attr('checked', true);
                /* var price = $('#radio_' + id).attr('price');
                 var delta = 
                 var total = parseInt(((val - 1) * price).toFixed(0),10);
                 totalTotal -= total 
                 $('#total').html(totalTotal);*/
                calTotal();

            })
            .on('click', '.spin-plus', function() {
                var id = $(this).attr("id");
                id = id.replace("plus_", "");
                var val = parseInt($('#spin-value_' + id).val(), 10);
                if (val >= 9999) {
                    val = 9999
                    $('#spin-value_' + id).val(9999);
                } else {
                    val = val + 1;
                    $('#spin-value_' + id).val(val);
                }
                $('#check_' + id).prop('checked', true);
                calTotal();
            });
    }
    var initShopcarPage = function() {

        /*       shopcar的定义
                shopcar["wineImg"] 
                 shopcar["wineName"]
                 shopcar["winePrice"] 
                 shopcar["wineOverseasPrice"]
                 shopcar["id"]*/
        var shop =
            '<dl id="#id#" carid="#carid#" price="#winePrice#">' +
            '<dt class="box"><input type="checkbox" price="#winePrice#" name="shopcar" id="check_#id#" value="#id#">' +
            '<a href="javascript:void(0)"><img src="#wineImg#"></dt>' +
            '<dd>' +
            '<ul>' +
            '<li><a href="wine_detail.html?wineId=#id#" class="entry_title font_zise">#wineName#</a></li>' +
            '<li><b>￥#winePrice#</b>/<span>£#wineOverseasPrice#</span></li>' +
            '<li>' +
            '<label>数量(箱)</label>' +
            '<a href="javascript:void(0)" id="minus_#id#" class="bor_Rnone spin-minus">-</a>' +
            '<span><input type="text" class="bb_inpNO" value="#num#" maxlength="5" name="wineNum" id="spin-value_#id#" /></span>' +
            '<a href="javascript:void(0)" id="plus_#id#" class="bor_Lnone spin-plus">+</a>' +
            '<em><a href="#" wineId="#id#" carid="#carid#" class="dele"><img src="../images/del_icon.png">删除</a></em>' +
            '</li>' +
            '</ul>' +
            '</dd>' +
            '</dl>';
        var ajaxUrl = wineApp.CONFIG.API.cartget;
        wineApp.ajax.post(ajaxUrl, {}).done(function(data) {
            var key = wineApp.tool.getKey('check_shopingcar');
            if (data.list.length > 0) {
                wineApp.localStorage.set(key, 'Y');
            }

            $.each(data.list, function(index, value) {
                var tmp = shop;
                var shopcar = {};
                shopcar["wineImg"] = resourceURL + "/" + value.titleimg;
                shopcar["wineName"] = value.proname;
                shopcar["winePrice"] = value.price;
                shopcar["wineOverseasPrice"] = value.oprice;
                shopcar["id"] = value.prodid;
                shopcar["num"] = value.num;
                shopcar["carid"] = value.id;
                shopcarList.push(shopcar);
                for (var prop in shopcar) {
                    var reg = new RegExp("#" + prop + "#", "gm");
                    tmp = tmp.replace(reg, shopcar[prop]);
                }
                totalTotal += parseInt((shopcar.num * shopcar.winePrice * countPerSet).toFixed(0), 10);

                $('.wine_shopcar').prepend(tmp);
            });
            //$('#total').html(totalTotal);
        });
    }

    var calTotal = function() {
        var items = $('.wine_shopcar dl');
        var total = 0
        $.each(items, function(index, val) {
            var isChecked = $(this).find('input:checked').length > 0;
            if (!isChecked) return false;
            var id = $(this).attr('id');
            var val = parseInt($('#spin-value_' + id).val(), 10);
            var price = parseInt($(this).attr('price'), 10);
            total += price * val * countPerSet;
        });
        $('#total').html(total.toFixed(0));
        totalTotal = total;
        //return total.toFixed(0);
    }
    var createOrder = function() {

        var selectedPlans = $("input[name='shopcar']:checked");
        console.log('selectedPlans:%O', selectedPlans);
        if (selectedPlans.length < 1) {
            //wineApp.tool.toastError('请选择一条记录');
            layer.open({
                content: '请选择一条记录',
                btn: '确定'
            });
            return;
        }
        //var key = wineApp.tool.getKey("shopcar");
        //var shopcarHistory = wineApp.localStorage.get(key);
        if (_.isEmpty(shopcarList)) {
            //wineApp.tool.toastError('购物车没有商品，无须结算');
            layer.open({
                content: '购物车没有商品，无须结算',
                btn: '确定'
            });
            return;
        }
        if (totalTotal != 3000) {
            layer.open({
                content: '总价必须等于3000元',
                btn: '确定'
            });
            //wineApp.tool.toastError('总价必须等于3000元');
            return;
        }

        var param = [];
        var items = $('.wine_shopcar dl');
        console.log('items:%O', items);
        $.each(items, function(index, val) {
            var isChecked = $(this).find('input:checked').length > 0;
            if (!isChecked) return false;
            var wineId = $(this).attr('id');
            var planInfo = _.find(shopcarList, function(plan) {
                return plan.id == wineId;
            });
            if (_.isNil(planInfo)) {
                return false;
            }
            var val = parseInt($('#spin-value_' + wineId).val(), 10);
            var price = parseInt($(this).attr('price'), 10);
            var amount = price * val * countPerSet;
            var obj = {
                count: val,
                prodid: wineId,
                ammount: amount,
                wineName: planInfo.wineName,
                wineImg: planInfo.wineImg,
                winePrice: planInfo.winePrice,
                wineOverseasPrice: planInfo.wineOverseasPrice,
                id: planInfo.wineId,
                cartid: planInfo.carid
            };
            param.push(obj);
        });
        wineApp.orderutil.createProdObjToStorage(param, 'shopcar');
        window.location.href = 'order.html';
        // var ajaxUrl = wineApp.CONFIG.API.createorder;
        // wineApp.ajax.post(ajaxUrl, {
        //     param: JSON.stringify(param),
        //     userId: userInfo.platUser.id
        // }, function(data) {
        //     if (data.st == 'ok') {
        //         var orderId = data.msg;
        //         var key = wineApp.tool.getKey("shopcar");
        //         wineApp.localStorage.remove(key);
        //         var order = orderId.split(',');
        //         $.each(order, function(index, val) {
        //             if (addrId != '') {
        //                 var url = wineApp.CONFIG.API.orderaddr;
        //                 wineApp.ajax.post(url, {
        //                     addId: addrId,
        //                     orderId: val
        //                 }, function(data) {
        //                     console.log(data);
        //                 });
        //                 //window.location.href = 'mydj_list.html?type=WAIT_PAY';
        //             }
        //         });
        //         window.location.href = 'order_more.html?orderId=' + orderId
        //     }
        // })
    }

    var loadAddr = function() {
        var ajaxUrl = wineApp.CONFIG.API.addresslist + '?userId=' + userInfo.platUser.id;
        wineApp.ajax.get(ajaxUrl, function(data) {
            console.log(data);
            if (data.st == 'ok') {
                $.each(data.msg, function(index, val) {
                    if (val.isDefault == "1") {
                        addrId = val.id;
                    }
                });
            }
        })
    }

    var initEvent = function() {
        $(document).on('click', '#pay', createOrder);
        $(document).on('click', '#all', function() {
            var all = $('input[name="shopcar"]');
            var checkedAll = $('#all').is(':checked');
            $.each(all, function(index, checkBox) {
                $(checkBox).prop('checked', checkedAll);
            })
            calTotal();
        }).on('click', 'input[name="shopcar"]', function() {
            calTotal();
        }).on('click', '.box', function() {
            var $checkBox = $(this).find('input[name="shopcar"]')

            var checked = $checkBox.is(':checked');
            console.log(checked);
            $checkBox.prop('checked', !checked)
        });
        $(document).on('click', '.dele', function() {
            // var key = wineApp.tool.getKey("shopcar");

            // var shopcarHistory = wineApp.localStorage.get(key);
            // if ($.isEmptyObject(shopcarHistory)) {
            //     wineApp.localStorage.set(key, []);
            //     shopcarHistory = [];
            // };
            // var idx = -1;
            // //如果ID重复数量合并
            var id = $(this).attr('carid');
            // console.log(id);
            // var shopcard = _.filter(shopcarHistory, function(car) {
            //     return car.id != id;
            // })
            // if (shopcard == null) {
            //     shopcard = [];
            // }
            // wineApp.localStorage.remove(key);
            // wineApp.localStorage.set(key, shopcard);
            var ajaxUrl = wineApp.CONFIG.API.cartdeletebyid
            wineApp.ajax.post(ajaxUrl, {
                id: id
            }).done(function(data) {
                $('.wine_shopcar dl[carid=' + id + ']').remove();
                calTotal();
                if ($('.wine_shopcar dl').length == 0) {
                    var key = wineApp.tool.getKey('check_shopingcar');
                    wineApp.localStorage.set(key, 'N');
                }
            });

        });
    }
    return {
        initPage: initPage
    }

})();

$(document).ready(function() {
    $('.wine_footer').remove();
    wineApp.common.initHeaderIcon(0, true, {
        camera: false,
        search: false
    });
    wineApp.shopcar.initPage();
});